package com.chengv.redismq.config;

import com.chengv.redismq.serializer.ObjectJackson2JsonRedisSerializer;
import org.redisson.spring.starter.RedissonAutoConfiguration;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;

/**
 * 自定义 Redis 配置
 *
 * @author chengv
 */
@AutoConfiguration(before = RedissonAutoConfiguration.class)
public class MyRedisAutoConfiguration {

    /**
     * 覆盖默认的 {@link RedissonAutoConfiguration#redisTemplate(RedisConnectionFactory)} Bean
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(factory);
        // Key 使用 String 序列化方式
        redisTemplate.setKeySerializer(RedisSerializer.string());
        redisTemplate.setHashKeySerializer(RedisSerializer.string());
        // Value 使用 JSON 序列化方式
        redisTemplate.setValueSerializer(new ObjectJackson2JsonRedisSerializer());
        redisTemplate.setHashValueSerializer(new ObjectJackson2JsonRedisSerializer());
        return redisTemplate;
    }
}
